# GO-AGENT 停止脚本 (PowerShell版本)
Write-Host "===========================================" -ForegroundColor Green
Write-Host "           GO-AGENT 停止脚本" -ForegroundColor Green
Write-Host "===========================================" -ForegroundColor Green
Write-Host

Write-Host "正在查找运行中的 go-agent 进程..." -ForegroundColor Yellow

# 获取所有 go-agent 相关进程
$processes = Get-Process | Where-Object { $_.ProcessName -like "*go-agent*" }

if ($processes.Count -eq 0) {
    Write-Host "未发现运行中的 go-agent 进程" -ForegroundColor Green
    Write-Host
    Write-Host "停止脚本执行完毕" -ForegroundColor Green
    Write-Host "===========================================" -ForegroundColor Green
    Read-Host "按 Enter 键退出"
    exit
}

Write-Host "发现以下 go-agent 进程:" -ForegroundColor Cyan
$processes | Format-Table ProcessName, Id, CPU, WorkingSet -AutoSize

Write-Host "正在强制结束所有 go-agent 相关进程..." -ForegroundColor Yellow

$successCount = 0
$failCount = 0

foreach ($process in $processes) {
    try {
        Write-Host "结束进程: $($process.ProcessName) (PID: $($process.Id))" -ForegroundColor White
        Stop-Process -Id $process.Id -Force -ErrorAction Stop
        $successCount++
        Write-Host "✅ 进程 $($process.Id) 已结束" -ForegroundColor Green
    }
    catch {
        Write-Host "❌ 无法结束进程 $($process.Id): $($_.Exception.Message)" -ForegroundColor Red
        $failCount++
    }
}

Write-Host
Write-Host "等待进程完全结束..." -ForegroundColor Yellow
Start-Sleep -Seconds 2

# 再次检查
$remainingProcesses = Get-Process | Where-Object { $_.ProcessName -like "*go-agent*" }

if ($remainingProcesses.Count -eq 0) {
    Write-Host "✅ 所有 go-agent 进程已成功结束" -ForegroundColor Green
} else {
    Write-Host "⚠️  仍有 $($remainingProcesses.Count) 个进程未结束:" -ForegroundColor Red
    $remainingProcesses | Format-Table ProcessName, Id -AutoSize
}

Write-Host
Write-Host "执行结果:" -ForegroundColor Cyan
Write-Host "  成功结束: $successCount 个进程" -ForegroundColor Green
Write-Host "  结束失败: $failCount 个进程" -ForegroundColor Red

Write-Host
Write-Host "停止脚本执行完毕" -ForegroundColor Green
Write-Host "===========================================" -ForegroundColor Green
Read-Host "按 Enter 键退出"